package W072_081.src.controller;

import W071.src.util.JSONUtil;
import W072_081.src.dao.TeacherService;
import W072_081.src.entity.Teacher;
import W072_081.src.exception.BaseException;
 // 修改导入语句
import W072_081.src.util.Condition;
import W072_081.src.util.ControllerHelper;
import W072_081.src.util.Pagination;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/tc")
public class TeacherReadCtl extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject messageJsonObj = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
        String reqJsonStr = JSONUtil.getJSON(request);
        JSONObject reqJsonObj = JSON.parseObject(reqJsonStr);
        if (reqJsonObj == null) {
            messageJsonObj.put("message", "未收到请求信息！");
            response.getWriter().println(messageJsonObj);
            return;
        }
        try {
            Pagination pagination = ControllerHelper.getPagination(reqJsonObj);
            List<Condition> conditionList = ControllerHelper.getConditions(reqJsonObj); // 确保这里使用的是 util.Condition
            Collection<Teacher> teachers = TeacherService.getInstance().findAll(conditionList, pagination);
            messageJsonObj.put("totalNum", pagination.getTotalNum());
            messageJsonObj.put("records", teachers);
            response.getWriter().println(messageJsonObj);
        } catch (BaseException e) {
            messageJsonObj.put("message", e.getMessage());
            response.getWriter().println(messageJsonObj);
            e.printStackTrace();
        } catch (SQLException e) {
            messageJsonObj.put("message", "数据库操作异常！");
            response.getWriter().println(messageJsonObj);
            e.printStackTrace();
        } catch (Exception e) {
            messageJsonObj.put("message", "网络异常！");
            response.getWriter().println(messageJsonObj);
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}